#!/usr/bin/env python
"""
Acorn-SDR (A Collaboration of Radio Nodes)
(c) Bob Cowdery (G3UKB) 2009

File: dsp_service.py
Date: January 2009

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

================================================================================
Module Description:

The dttsp service.

"""

#-------------------------------------------------------------------------------
# System imports
import sys
import os
from Numeric import *
from time import sleep
from scipy import signal
import Ice, IceStorm

# Application imports
import libdttsp
import ice_helpers
import utils
import dttsp
from dttsp_map import *

# Import the Ice interface definitions
import AcornLifeCycle
import AcornRxUpdate
import AcornRxDsp
import AcornIqIn
import AcornRxOut
import AcornPersist
import AcornRxDisplays

#===============================================================================
# Ice life-cycle events for the GUI
class LifeCycleI(AcornLifeCycle.LifeCycle):
    
    #---------------------------------------------------------------------------   
    def __init__(self, dttsp, service):
        self.dttsp = dttsp
        self.service = service
        self.dttsp.start()
      
    #---------------------------------------------------------------------------
    def start(self, current=None):
        # For now don't start/stop here as the restart is faulty
        # It works fine to leave the dsp running from init to terminate
        #self.dttsp.start()
        pass
     
    #---------------------------------------------------------------------------   
    def stop(self, current=None):
        #self.dttsp.stop()
        pass
    
    #---------------------------------------------------------------------------    
    def terminate(self, current=None):
        self.dttsp.stop()
        self.service.terminate()
        
#===============================================================================
# Commands for the DSP
class RxDspI(AcornRxDsp.RxDsp):
    
    #---------------------------------------------------------------------------   
    def __init__(self, dttsp, service):
        self.dttsp = dttsp
        self.service = service
        self.filter = '2K1'
        self.mode = 'LSB'
        
    #---------------------------------------------------------------------------
    def setMode(self, mode, current=None):
        self.dttsp.mode(mode)
    
    #---------------------------------------------------------------------------    
    def setFilter(self, filter, current=None):
        self.dttsp.filter(filter)
    
    #---------------------------------------------------------------------------    
    def setAgc(self, mode, current=None):
        self.dttsp.agc(mode)
        
    #---------------------------------------------------------------------------    
    def setGain(self, gain, current=None):
        self.dttsp.af_gain(gain)
    
    #---------------------------------------------------------------------------    
    def oscSet(self, offset, current=None):
        self.dttsp.osc_set(offset)
        
    #---------------------------------------------------------------------------    
    def oscInc(self, inc, current=None):
        self.dttsp.osc_inc(inc)
        
    #---------------------------------------------------------------------------    
    def setRxPan(self, value, current=None):
        self.dttsp.pan(value)
    
    #---------------------------------------------------------------------------    
    def setRxListen(self, radio, current=None):
        self.dttsp.listen(radio)
        
    #---------------------------------------------------------------------------    
    def setRxOn(self, radio, current=None):
        self.dttsp.rx_on(radio)
        
    #---------------------------------------------------------------------------    
    def setRxOff(self, radio, current=None):
        self.dttsp.rx_off(radio)
        
    #---------------------------------------------------------------------------    
    def setBin(self, state, current=None):
        self.dttsp.bin(state)
        
    #---------------------------------------------------------------------------    
    def setNr(self, state, current=None):
        self.dttsp.nr(state)
        
    #---------------------------------------------------------------------------    
    def setNb(self, state, current=None):
        self.dttsp.nb(state)
        
    #---------------------------------------------------------------------------    
    def setAnf(self, state, current=None):
        self.dttsp.anf(state)
    

#===============================================================================
# Ice config events for the DSP
class RxConfigI(AcornRxUpdate.RxConfig):
    
    #---------------------------------------------------------------------------   
    def __init__(self, dttsp, persist, config_map):
        self.dttsp = dttsp
        self.persist = persist
        self.map = config_map
      
    #---------------------------------------------------------------------------   
    def configUpdate(self, name, current=None):
        pass
        # Update the DSP configuration
        # We don't deal with changing the output streaming at the moment (restart)
        if name in self.map:
            # Its something we are interested in so go get it
            item = utils.persist_get(self.persist, 'Profile', name)
            # and pass it in
            self.map[name](item)
        
#===============================================================================
# Receiver for the audio stream
class IqInI(AcornIqIn.IqIn):
    
    #---------------------------------------------------------------------------
    def __init__(self, dttsp, stream_out, ozy_out, stream_to):
        self.dttsp = dttsp
        self.stream_out = stream_out
        self.ozy_out = ozy_out
        self.stream_to = stream_to
    
    #---------------------------------------------------------------------------   
    def data(self, samples, current=None):
        # do the conversion of samples here
        # Run one DSP cycle
        samples_as_double = asarray(samples, 'd')
        #print 'Input: ', samples_as_double[0][:20]
        real_out = self.dttsp.process(samples_as_double[0], samples_as_double[1])
        #print 'Output: ', real_out[0][:20]
        #sleep(0.02)
        #real_out_as_float = asarray(real_out, 'f')
        #real_out_as_float = real_out.astype('f')
        # Move the samples to the output stream
        if self.stream_to == 'mercury' or self.stream_to == 'mercury+soundcard':
            self.ozy_out.data(real_out.tolist())
            #print 'Sent: ', real_out.tolist()
            #print real_out.tolist()
        if self.stream_to == 'soundcard' or self.stream_to == 'mercury+soundcard':
            # This goes to Jack
            self.stream_out.data(real_out.tolist())
        # Apply any updates we received
        #self.dsp_impl.apply_updates()
                
#===============================================================================
class DttSpService(Ice.Application):
    
    #---------------------------------------------------------------------------
    def __init__(self):       
        self.close = False
    
    #---------------------------------------------------------------------------
    # Run the app
    def run(self, args):
       
       #-----------------------------------------------------------------------
        # persist interface
        persist = ice_helpers.get_interface('DttSp Service', self.communicator, AcornPersist.PersistPrx, 'Persist.Proxy')
        # Get config
        ramp = utils.persist_get(persist, 'Profile', 'dsp.agcramp')
        gain = utils.persist_get(persist, 'Profile', 'dsp.agcgain')
        roof = utils.persist_get(persist, 'Profile', 'dsp.agcroof')
        frames = utils.persist_get(persist, 'Profile', 'audio.frames')
        rate = utils.persist_get(persist, 'Profile', 'audio.rate')
        stream_to = utils.persist_get(persist, 'Profile', 'audio.output')
        rf_gain = utils.persist_get(persist, 'Dynamic', 'gain')
        
        #-----------------------------------------------------------------------
        # Event names used here
        publish_to_rx_updates = 'rx_update_events'
        publish_to_rx_display = 'rx_display_events'
        subscribe_to_rx_config = 'rx_config_events'
        subscribe_to_rx_dsp = 'rx_dsp_events'
        subscribe_to_lc = 'life_cycle_events'
  
        #-----------------------------------------------------------------------
        # This is the same for both publishers and subscribers
        # Get the IceStorm topic manager interface
        manager = ice_helpers.get_topic_manager('DttSp Service', self.communicator)
        
        # Retrieve the subscriber topic
        rx_dsp_topic = ice_helpers.get_topic('DttSp Service', manager, subscribe_to_rx_dsp)
        life_cycle_topic = ice_helpers.get_topic('DttSp Service', manager, subscribe_to_lc)
        rx_config_topic = ice_helpers.get_topic('DttSp Service', manager, subscribe_to_rx_config)
        
        # Retrieve the publisher topic
        rx_update_topic = ice_helpers.get_topic('DttSp Service', manager, publish_to_rx_updates)
        rx_display_topic = ice_helpers.get_topic('DttSp Service', manager, publish_to_rx_display)
  
        #-----------------------------------------------------------------------
        # Publisher side
        # Get the update topic's publisher object, and create an update proxy
        publisher_1 = rx_update_topic.getPublisher();
        publisher_1 = publisher_1.ice_oneway();        
        rx_update_publisher = AcornRxUpdate.RxUpdatePrx.uncheckedCast(publisher_1)
        
        # Get the display topic's publisher object, and create a display proxy
        publisher_2 = rx_display_topic.getPublisher();
        publisher_2 = publisher_2.ice_oneway();        
        rx_display_publisher = AcornRxDisplays.RxDisplaysPrx.uncheckedCast(publisher_2)
        
        #-----------------------------------------------------------------------
        # Initialise the Dsp as its needed for the adapter and requires the update publisher
        dttsp_impl = dttsp.Dsp(persist, rx_update_publisher, rx_display_publisher, frames, rate)
        # Set up a map for updates
        config_map = {'audio.frames': dttsp_impl.set_audioframes, 'audio.rate': dttsp_impl.set_audiorate}
        
        #-----------------------------------------------------------------------
        # Subscriber side
        # Create an adapter for the subscriber dsp interface
        adapter_1 = self.communicator().createObjectAdapter("RxDsp.Subscriber")
        subId_1 = Ice.Identity()
        subId_1.name = Ice.generateUUID()
        # Add the update interface to the adapter
        subscriber_1 = adapter_1.add(RxDspI(dttsp_impl, self), subId_1)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('DttSp Service', rx_dsp_topic, subscriber_1, id)
        # Now we can receive callbacks   
        adapter_1.activate()
        
        adapter_2 = self.communicator().createObjectAdapter("LifeCycle.Subscriber")
        subId_2 = Ice.Identity()
        subId_2.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_2 = adapter_2.add(LifeCycleI(dttsp_impl, self), subId_2)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('DttSp Service', life_cycle_topic, subscriber_2, id)
        # Now we can receive callbacks   
        adapter_2.activate()
        
        adapter_3 = self.communicator().createObjectAdapter("RxConfig.Subscriber")
        subId_3 = Ice.Identity()
        subId_3.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_3 = adapter_3.add(RxConfigI(dttsp_impl, persist, config_map), subId_3)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('DttSp Service', rx_config_topic, subscriber_3, id)
        # Now we can receive callbacks   
        adapter_3.activate()
        
        #-----------------------------------------------------------------------
        # One way audio channel out
        # Set up the proxy
        # The stream can be split for remote HPSDR or single
        ozy_out = None
        stream_out = None
        if stream_to == 'mercury' or stream_to == 'mercury+soundcard':
            ozy_out = ice_helpers.get_interface('DSP Service', self.communicator, AcornRxOut.RxOutPrx, 'OzyOut.Proxy')
            ozyStreamOneway = AcornRxOut.RxOutPrx.uncheckedCast(ozy_out.ice_oneway())
        if stream_to == 'soundcard' or stream_to == 'mercury+soundcard':
            stream_out = ice_helpers.get_interface('DttSp Service', self.communicator, AcornRxOut.RxOutPrx, 'RxOut.Proxy')
            streamOneway = AcornStreamOut.StreamOutPrx.uncheckedCast(stream_out.ice_oneway())
        
        #-----------------------------------------------------------------------
        # One way audio channel in
        audio_adapter = self.communicator().createObjectAdapter("IqIn")
        audio_adapter.add(IqInI(dttsp_impl, stream_out, ozy_out, stream_to), self.communicator().stringToIdentity("iqin"))       
        # Now we can receive callbacks for audio 
        audio_adapter.activate()
        sleep(2)
        
        print 'Acorn-SDR (DttSp Service) running..'
        
        #-----------------------------------------------------------------------
        # Wait for closedown
        while not self.close:
            # Idle loop for doing any other work
            sleep(1)

        # Unsubscribe all subscribed objects.
        # Causes an error?
        #rx_dsp_topic.unsubscribe(subscriber_1)
        #life_cycle_topic.unsubscribe(subscriber_2)
        #rx_config_topic.unsubscribe(subscriber_3)
    
    #---------------------------------------------------------------------------
    # Terminate
    def terminate(self):
        self.close = True
        
#===============================================================================
#===============================================================================
# Start from the command line
if __name__ == "__main__":
   
    app = DttSpService()
    app.main(sys.argv, sys.argv[1])
  
    # Announce we are going 
    print 'Acorn-SDR  (DttSp Service) closing..'


